package cn.huiyunche.base.service.framework.utils;


import cn.huiyunche.base.service.model.DWaybill;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.TmsQueueDriverIndexVo;
import cn.huiyunche.base.service.vo.TmsQueueDriverRtnVo;
import cn.huiyunche.base.service.vo.TmsQueueDriverVo;
import cn.huiyunche.base.service.vo.TmsQueueOrderVo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 人送队列 管理工具
 *
 * @author hdy [Tuffy]
 */
public class TmsQueueApi {

	/** 中联人送司机 key*/
	private static final String ZL_RS_DRIVER = "ZL_RS_DRIVER";
	/** 中联人送司机 临时司机key*/
	private static final String ZL_RS_DRIVER_TEMPORARY = "ZL_RS_DRIVER_TEMPORARY";
	/** 中联人送订单 key*/
	private static final String ZL_RS_ORDER = "ZL_RS_ORDER";
	/** 中联人送急发订单 key*/
	private static final String ZL_RS_QUICK_ORDER = "ZL_RS_QUICK_ORDER";
	/** 排队队列*/
	private static final String ZL_RS_INDEX = "ZL_RS_INDEX";
	/** 意向路线短信队列*/
	private static final String ZL_RS_INTENTIONALLINES_PHONE = "ZL_RS_INTENTIONALLINES_PHONE";
	/** 提醒报警队列*/
	private static final String ZL_RS_SYSTEM_WARING = "ZL_RS_SYSTEM_WARING";
	/** 提醒报警队列 超时时间戳 半天*/
	private static final long ZL_RS_SYSTEM_WARING_TIMER = 12 * 60 * 60 * 1000 * 1;
	/** redis 连接对象*/
	private static Jedis jedis = null;
	/**是否开始派单*/
	private static Boolean IS_START_QUEUE = false;
	/**是否全局开始派单*/
	private static Boolean ROOT_QUEUE_IS_START = false;
	/** 中联人送司机意向方向 key*/
	private static final String ZL_RS_DRIVER_PURPOSE = "ZL_RS_DRIVER_PURPOSE";

	/**
	 * 查看是否已经发送短信
	 * @return
	 */
	public static boolean isSendSystemWaringMessage() {
		jedis = HYCUtils.getJedis();
		try {
			String value = jedis.get(ZL_RS_SYSTEM_WARING);
			if (StringUtils.isNotBlank(value)) {
				long timer = NumberUtils.toLong(value);
				if (new Date().getTime() - timer <= ZL_RS_SYSTEM_WARING_TIMER) {
					return true;
				}
			}
			return false;
		} finally {
			jedis.close();
		}
	}

	/**
	 * 追加发送短信标记
	 */
	public static void addSendSystemWaringMessageFlag() {
		jedis = HYCUtils.getJedis();
		try {
			jedis.set(ZL_RS_SYSTEM_WARING, new Date().getTime() + "");
		} finally {
			jedis.close();
		}
	}

	/**
	 * 判断是否存在司机意向路线不匹配短信记录
	 * @param phone 手机号
	 * @return 是否存在
	 */
	public static boolean isExistDriverIntentionaLines(String phone) {
		jedis = HYCUtils.getJedis();
		try {
			Long lengthTem = getQueueLength(ZL_RS_INTENTIONALLINES_PHONE);
			for (long i = 0; i < lengthTem; i++) {
				String data = getDataByIndex(ZL_RS_INTENTIONALLINES_PHONE, i);
				if (StringUtils.isNotBlank(data)) {
					if (data.contains(phone)) {
						return true;
					}
				}
			}
			return false;
		} finally {
			jedis.close();
		}
	}

	/**
	 * 追加意向路线短信发送
	 * @param phone 手机号
	 */
	public static void appendDriverIntentionaLines(String phone) {
		jedis = HYCUtils.getJedis();
		try {
			removeDriverIntentionaLines(phone);
			append(ZL_RS_INTENTIONALLINES_PHONE, phone + ";" + new Date().getTime());
		} finally {
			jedis.close();
		}
	}

	/**
	 * 获取下一个订单
	 * @return 数据对象
	 */
	public static TmsQueueOrderVo getNextOrder() {
		jedis = HYCUtils.getJedis();
		try {
			String next = getNext(ZL_RS_ORDER);
			if (StringUtils.isBlank(next)) {
				return null;
			}
			return JSONObject.parseObject(next, TmsQueueOrderVo.class);
		} finally {
			jedis.close();
		}
	}

	/**
	 * 通过索引 获取司机信息
	 * @param index 索引
	 * @return 司机队列信息
	 */
	public static TmsQueueDriverVo getDriverByIndex(long index) {
		jedis = HYCUtils.getJedis();
		try {
			String data = getDataByIndex(ZL_RS_DRIVER, index);
			return JSONObject.parseObject(data, TmsQueueDriverVo.class);
		}  finally {
			jedis.close();
		}
	}

	/**
	 *  获取下一个司机
	 * @param isFirst 是否是第一次获取。如果是第一次获取则将缓存队列中数据推到司机队列中；如果不是第一次获取则从司机队列中获取
	 * @return 数据对象
	 */
	public static TmsQueueDriverVo getNextDriver(boolean isFirst) {
		jedis = HYCUtils.getJedis();
		try {
			// 第一次获取数据
			if (isFirst) {
				moveTemporary2Driver();
			// 第二次以后获取数据
			} else {
				String first = getNext(ZL_RS_DRIVER);
				moveDriver2Temporary(first);
				remove(ZL_RS_DRIVER, first);
			}
			String value = getNext(ZL_RS_DRIVER);
			if (StringUtils.isNotBlank(value)) {
				return JSONObject.parseObject(value, TmsQueueDriverVo.class);
			}
			return null;
		} finally {
			jedis.close();
		}
	}

	/**
	 * 获取司机
	 * @param phone 手机号
	 * @return 司机扩展对象
	 */
	public static TmsQueueDriverRtnVo getNextDriver(String phone) {
		jedis = HYCUtils.getJedis();
		try {
			Long lengthTem = getQueueLength(ZL_RS_DRIVER_TEMPORARY);
			for (long i = 0; i < lengthTem; i++) {
				String data = getDataByIndex(ZL_RS_DRIVER_TEMPORARY, i);
				if (StringUtils.isNotBlank(data)) {
					TmsQueueDriverVo tqdv = JSONObject.parseObject(data, TmsQueueDriverVo.class);
					if (tqdv.getPhone().equals(phone)) {
						TmsQueueDriverRtnVo tqdrv = new TmsQueueDriverRtnVo();
						BeanUtils.copyProperties(tqdv, tqdrv);
						tqdrv.setIndex(i);
						tqdrv.setOrderNumber(getQueueLength(ZL_RS_ORDER));
						return tqdrv;
					}
				}
			}
			Long length = getQueueLength(ZL_RS_DRIVER);
			for (long i = 0; i < length; i++) {
				String data = getDataByIndex(ZL_RS_DRIVER, i);
				if (StringUtils.isNotBlank(data)) {
					TmsQueueDriverVo tqdv = JSONObject.parseObject(data, TmsQueueDriverVo.class);
					if (tqdv.getPhone().equals(phone)) {
						TmsQueueDriverRtnVo tqdrv = new TmsQueueDriverRtnVo();
						BeanUtils.copyProperties(tqdv, tqdrv);
						if (null == lengthTem) {
							lengthTem = 0L;
						}
						tqdrv.setIndex(i + lengthTem);
						tqdrv.setOrderNumber(getQueueLength(ZL_RS_ORDER));
						return tqdrv;
					}
				}
			}
		} finally {
			jedis.close();
		}
		return null;
	}

	/**
	 * 追加订单到队列
	 * @param eov 数据对象
	 */
	public static void appendOrder(TmsQueueOrderVo eov) {
		jedis = HYCUtils.getJedis();
		try {
                eov.setTime(DateUtils.getStringFromDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                Boolean isUrgent = eov.getUrgent();
                String resource = JSONObject.toJSONString(eov);
                System.out.println("==========resource==========" + resource);
                // 普通
                if (null == isUrgent || !isUrgent) {
                    append(ZL_RS_ORDER, resource);
                    return;
                }
                // 加急
                jedis.lpush(ZL_RS_ORDER, resource);

		} finally {
			jedis.close();
		}
	}

	/**
	 * 追加订单到队列
	 * @param waybills 数据对象
	 */
	public static void appendOrders(List<DWaybill> waybills) {
		jedis = HYCUtils.getJedis();
		try {

            if ( CollectionUtils.isNotEmpty(waybills) ) {
                waybills.stream().forEach(bill -> {

                    String waybillId = bill.getId().toString();
                    String tmsSerialNo = bill.getOrderLineId().toString();

                    Long lengthTem = getQueueLength(ZL_RS_ORDER);

                    boolean exist = false;

                    if( 0 != lengthTem){
                        for (long i = 0; i < lengthTem; i++) {
                            String data = getDataByIndex(ZL_RS_ORDER, i);
                            if (StringUtils.isNotBlank(data)) {
                                TmsQueueOrderVo tqov = JSONObject.parseObject(data, TmsQueueOrderVo.class);
                                // 防止null导致系统异常
                                if (StringUtils.isBlank(waybillId)) {
                                    waybillId = "";
                                }
                                if (StringUtils.isBlank(tmsSerialNo)) {
                                    tmsSerialNo = "";
                                }
                                if (tqov.getWaybillId().equals(waybillId) || tqov.getTmsSerialNo().equals(tmsSerialNo)) {
                                    exist = true;
                                }
                            }
                        }
                    }

                    if( !exist ){
                        //如果不存在则添加运单到队列
                        TmsQueueOrderVo eov = new TmsQueueOrderVo();
                        eov.setWaybillId(bill.getId().toString());
                        eov.setTmsSerialNo(bill.getOrderLineId().toString());
                        eov.setFrom(bill.getDepartureCity());
                        eov.setTo(bill.getDestCity());
                        eov.setUrgent(bill.getIsUrgent());
                        eov.setTime(DateUtils.getStringFromDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        Boolean isUrgent = eov.getUrgent();
                        String resource = JSONObject.toJSONString(eov);
                        System.out.println("==========resource==========" + resource);
                        // 普通
                        if (null == isUrgent || !isUrgent) {
                            append(ZL_RS_ORDER, resource);
                            return;
                        }
                        // 加急
                        jedis.lpush(ZL_RS_ORDER, resource);
                    }
                });
            }
		} finally {
			jedis.close();
		}
	}

	/**
	 * 追加订单到队列头部
	 * @param eov 数据对象
	 */
	public static void appendOrder4First(TmsQueueOrderVo eov) {
		jedis = HYCUtils.getJedis();
		try {
			eov.setTime(DateUtils.getStringFromDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
			String resource = JSONObject.toJSONString(eov);
			System.out.println("=====appendOrder4Forst=====resource==========" + resource);
			jedis.lpush(ZL_RS_ORDER, resource);
		} finally {
			jedis.close();
		}
	}

	/**
	 * 追加司机到司机队列
	 * @param edv 数据对象
	 */
	public static void appendDriver(TmsQueueDriverVo edv) {
		jedis = HYCUtils.getJedis();
		try {
			removeDriverIndex(edv.getPhone());
			edv.setNubmer(addDriverIndex(edv.getPhone()));
			append(ZL_RS_DRIVER, JSONObject.toJSONString(edv));
		} finally {
			jedis.close();
		}
	}

	/**
	 * 添加意向方向
	 *
	 * @param addressVos
	 * @param phone
	 */
	public static void appendPurpose(TmsQueueDriverVo addressVos, String phone) {
		jedis = HYCUtils.getJedis();
		try {
			// 获取redis中司机意向方向长度
			Long lengthTem = getQueueLength(ZL_RS_DRIVER_PURPOSE);
			for (long i = 0; i < lengthTem; i++) {
				// 获取数据
				String data = getDataByIndex(ZL_RS_DRIVER_PURPOSE, i);
				if (StringUtils.isNotBlank(data)) {
					// 数据转换
					TmsQueueDriverVo tqdv = JSONObject.parseObject(data, TmsQueueDriverVo.class);
					if (tqdv.getPhone().equals(phone)) {
						// 如果存在则删除
						remove(ZL_RS_DRIVER_PURPOSE, data);
						break;
					}
				}
			}
			// 添加意向方向到redis中
			append(ZL_RS_DRIVER_PURPOSE, JSONObject.toJSONString(addressVos));
		} finally {
			jedis.close();
		}
	}

	/**
	 * 获取redis意向方向
	 *
	 * @return
	 */
	public static List<TmsQueueDriverVo> purposeList () {
		jedis = HYCUtils.getJedis();
		List<TmsQueueDriverVo> rtnList = new ArrayList<>();
		try {
			List<String> list = jedis.lrange(ZL_RS_DRIVER_PURPOSE, 0, -1);
			if (null != list) {
				for (String s: list) {
					rtnList.add(JSONObject.parseObject(s, TmsQueueDriverVo.class));
				}
			}
		} finally {
			jedis.close();
		}
		return rtnList;
	}

	/**
	 * 删除队列中指定订单对象
	 * @param eov 订单对象
	 */
	public static void removeOrder(TmsQueueOrderVo eov) {
		jedis = HYCUtils.getJedis();
		try {
			remove(ZL_RS_ORDER, JSONObject.toJSONString(eov));
		} finally {
			jedis.close();
		}
	}

	/**
	 * 删除队列中指定订单对象。运单id和tms流水号，那个方便传递哪个
	 * @param waybillId 运单id
	 * @param tmsSerialNo tms流水号
	 */
	public static void removeOrder(String waybillId, String tmsSerialNo) {
		jedis = HYCUtils.getJedis();
		try {
			Long lengthTem = getQueueLength(ZL_RS_ORDER);
			for (long i = 0; i < lengthTem; i++) {
				String data = getDataByIndex(ZL_RS_ORDER, i);
				if (StringUtils.isNotBlank(data)) {
					TmsQueueOrderVo tqov = JSONObject.parseObject(data, TmsQueueOrderVo.class);
					// 防止null导致系统异常
					if (StringUtils.isBlank(waybillId)) {
						waybillId = "";
					}
					if (StringUtils.isBlank(tmsSerialNo)) {
						tmsSerialNo = "";
					}
					if (tqov.getWaybillId().equals(waybillId) || tqov.getTmsSerialNo().equals(tmsSerialNo)) {
						remove(ZL_RS_ORDER, data);
						return;
					}
				}
			}
		} finally {
			jedis.close();
		}
	}

	/**
	 * 删除队列中指定司机对象
	 * @param edv 司机对象
	 */
	public static void removeDriver(TmsQueueDriverVo edv) {
		jedis = HYCUtils.getJedis();
		try {
			String driver = JSONObject.toJSONString(edv);
			remove(ZL_RS_DRIVER, driver);
			remove(ZL_RS_DRIVER_TEMPORARY, driver);
			/*if (null != edv) {
				removeDriverIndex(edv.getPhone());
			}*/
        } finally {
            jedis.close();
        }
    }

    /**
     * 删除司机排队信息
     *
     * @param phone 手机号
     */
    public static void removeDriver(String phone) {
        jedis = HYCUtils.getJedis();
        try {
            Long lengthTem = getQueueLength(ZL_RS_DRIVER_TEMPORARY);
            for (long i = 0; i < lengthTem; i++) {
                String data = getDataByIndex(ZL_RS_DRIVER_TEMPORARY, i);
                if (StringUtils.isNotBlank(data)) {
                    TmsQueueDriverVo tqdv = JSONObject.parseObject(data, TmsQueueDriverVo.class);
                    if (tqdv.getPhone().equals(phone)) {
                        remove(ZL_RS_DRIVER_TEMPORARY, data);
                        // removeDriverIndex(phone);
                        return;
                    }
                }
            }
            Long length = getQueueLength(ZL_RS_DRIVER);
            for (long i = 0; i < length; i++) {
                String data = getDataByIndex(ZL_RS_DRIVER, i);
                if (StringUtils.isNotBlank(data)) {
                    TmsQueueDriverVo tqdv = JSONObject.parseObject(data, TmsQueueDriverVo.class);
                    if (tqdv.getPhone().equals(phone)) {
                        remove(ZL_RS_DRIVER, data);
                        removeDriverIndex(phone);
                        return;
                    }
                }
            }
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取订单对象
     *
     * @param waybillId   运单id
     * @param tmsSerialNo 流水号
     * @return
     */
    public static TmsQueueOrderVo getOrder(String waybillId, String tmsSerialNo) {
        jedis = HYCUtils.getJedis();
        try {
            Long lengthTem = getQueueLength(ZL_RS_ORDER);
            for (long i = 0; i < lengthTem; i++) {
                String data = getDataByIndex(ZL_RS_ORDER, i);
                if (StringUtils.isNotBlank(data)) {
                    TmsQueueOrderVo tqov = JSONObject.parseObject(data, TmsQueueOrderVo.class);
                    // 防止null导致系统异常
                    if (StringUtils.isBlank(waybillId)) {
                        waybillId = "";
                    }
                    if (StringUtils.isBlank(tmsSerialNo)) {
                        tmsSerialNo = "";
                    }
                    if (tqov.getWaybillId().equals(waybillId) || tqov.getTmsSerialNo().equals(tmsSerialNo)) {
                        return tqov;
                    }
                }
            }
        } finally {
            jedis.close();
        }
        return null;
    }

    /**
     * 获取缓存订单数据
     *
     * @return 结果集
     */
    public static List<TmsQueueOrderVo> orderList() {
        jedis = HYCUtils.getJedis();
        List<TmsQueueOrderVo> rtnList = new ArrayList<>();
        try {
            List<String> list = jedis.lrange(ZL_RS_ORDER, 0, -1);
            if (null != list) {
                for (String s : list) {
                    rtnList.add(JSONObject.parseObject(s, TmsQueueOrderVo.class));
                }
            }
        } finally {
            jedis.close();
        }
        return rtnList;
    }

    /**
     * 获取缓存司机数据
     *
     * @return 结果集
     */
    public static List<TmsQueueDriverVo> driverList() {
        jedis = HYCUtils.getJedis();
        List<TmsQueueDriverVo> rtnList = new ArrayList<>();
        try {
            List<String> listTe = jedis.lrange(ZL_RS_DRIVER_TEMPORARY, 0, -1);
            if (null != listTe) {
                for (String s : listTe) {
                    rtnList.add(JSONObject.parseObject(s, TmsQueueDriverVo.class));
                }
            }
            List<String> list = jedis.lrange(ZL_RS_DRIVER, 0, -1);
            if (null != list) {
                for (String s : list) {
                    rtnList.add(JSONObject.parseObject(s, TmsQueueDriverVo.class));
                }
            }
        } finally {
            jedis.close();
        }
        return rtnList;
    }

    /**
     * 是否开始派单，静态变量
     *
     * @return
     */
    public static Boolean isStartQueue() {
        return IS_START_QUEUE;
    }

    /**
     * 重置派单状态
     *
     * @param isStartQueue 派单状态
     */
    public static void setStartQueue(Boolean isStartQueue) {
        IS_START_QUEUE = isStartQueue;
    }

    /**
     * 是否全局开始派单，静态变量
     *
     * @return
     */
    public static Boolean isRootStartQueue() {
        return ROOT_QUEUE_IS_START;
    }

    /**
     * 重置全局派单状态
     *
     * @param isRootStartQueue 派单状态
     */
    public static void setRootStartQueue(Boolean isRootStartQueue) {
        ROOT_QUEUE_IS_START = isRootStartQueue;
    }

    /**
     * 清除订单队列
     */
    public static void clearOrderQueue() {
        jedis = HYCUtils.getJedis();
        try {
            jedis.del(ZL_RS_ORDER);
        } finally {
            jedis.close();
        }
    }

    /**
     * 清除司机队列
     */
    public static void clearDriverQueue() {
        jedis = HYCUtils.getJedis();
        try {
            jedis.del(ZL_RS_DRIVER_TEMPORARY);
            jedis.del(ZL_RS_DRIVER);
        } finally {
            jedis.close();
        }
    }

    /**
     * 清除司机排号队列
     */
    public static void clearDriverIndexQueue() {
        jedis = HYCUtils.getJedis();
        try {
            jedis.del(ZL_RS_INDEX);
        } finally {
            jedis.close();
        }
    }

    /**
     * 加入排队
     *
     * @param phone
     */
    private static long addDriverIndex(String phone) {
        TmsQueueDriverIndexVo newTqdiv = new TmsQueueDriverIndexVo();
        Long index = getQueueLength(ZL_RS_INDEX);
        if (null == index) {
            index = 0L;
        }
        String lastData = getDataByIndex(ZL_RS_INDEX, index > 0 ? index - 1 : 0);
        long number = 1;
        Date d = new Date();
        newTqdiv.setPhone(phone);
        newTqdiv.setTime(d.getTime());
        if (StringUtils.isNotBlank(lastData)) {
            TmsQueueDriverIndexVo tqdiv = JSONObject.parseObject(lastData, TmsQueueDriverIndexVo.class);
            Long thisTimeBegin = DateUtils.getDate00ZeroDate(d).getTime();
            Long thisTimeEnd = DateUtils.getCurrent23ZeroDate().getTime();
            long time = tqdiv.getTime();
            // 当天
            if (thisTimeBegin <= time && time <= thisTimeEnd) {
                number = tqdiv.getNumber() + 1;
            }
        }
        newTqdiv.setNumber(number);
        append(ZL_RS_INDEX, JSONObject.toJSONString(newTqdiv));
        return number;
    }

    /**
     * 移除司机意向路线短信排队数据
     *
     * @param phone
     */
    public static void removeDriverIntentionaLines4User(String phone) {
        jedis = HYCUtils.getJedis();
        try {
            Long index = getQueueLength(ZL_RS_INTENTIONALLINES_PHONE);
            if (null == index) {
                return;
            }
            for (long i = 0; i < index; i++) {
                String data = getDataByIndex(ZL_RS_INTENTIONALLINES_PHONE, i);
                if (StringUtils.isNotBlank(data)) {
                    if (data.contains(phone)) {
                        remove(ZL_RS_INTENTIONALLINES_PHONE, data);
                        return;
                    }
                }
            }
        } finally {
            jedis.close();
        }
    }

    /**
     * 移除司机意向路线短信排队数据
     *
     * @param phone
     */
    private static void removeDriverIntentionaLines(String phone) {
        Long index = getQueueLength(ZL_RS_INTENTIONALLINES_PHONE);
        if (null == index) {
            return;
        }
        for (long i = 0; i < index; i++) {
            String data = getDataByIndex(ZL_RS_INTENTIONALLINES_PHONE, i);
            if (StringUtils.isNotBlank(data)) {
                if (data.contains(phone)) {
                    remove(ZL_RS_INTENTIONALLINES_PHONE, data);
                    return;
                }
            }
        }
    }

    /**
     * 移除排队数据
     *
     * @param phone
     */
    public static void removeDriverIndex(String phone) {
        long index = getQueueLength(ZL_RS_INDEX);
        for (long i = 0; i < index; i++) {
            String data = getDataByIndex(ZL_RS_INDEX, i);
            if (StringUtils.isNotBlank(data)) {
                TmsQueueDriverIndexVo tqdiv = JSONObject.parseObject(data, TmsQueueDriverIndexVo.class);
                if (tqdiv.getPhone().equals(phone)) {
                    remove(ZL_RS_INDEX, data);
                    return;
                }
            }
        }
    }

    /**
     * 获取指定队列长度
     *
     * @param key 空间名
     * @return 队列长度
     */
    private static Long getQueueLength(String key) {
        return jedis.llen(key);
    }

    /**
     * 获取指定索引数据
     *
     * @param key   空间名
     * @param index 索引
     * @return 结果集
     */
    private static String getDataByIndex(String key, Long index) {
        return jedis.lindex(key, index);
    }

    /**
     * 移动缓存队列数据到司机队列并清除缓存队列
     */
    private static void moveTemporary2Driver() {
        //  加入原队列
        List<String> list = jedis.lrange(ZL_RS_DRIVER_TEMPORARY, 0, -1);
        if (null != list) {
            int size = list.size();
            if (size > 0) {
                for (int i = size - 1; i >= 0; i--) {
                    jedis.lpush(ZL_RS_DRIVER, list.get(i));
                }
            }
        }
        // 删除缓存队列
        jedis.del(ZL_RS_DRIVER_TEMPORARY);
    }

    /**
     * 将司机队列中第一个数据移动到缓存队列
     *
     * @param value 数据对象
     */
    private static void moveDriver2Temporary(String value) {
        append(ZL_RS_DRIVER_TEMPORARY, value);
    }

    /**
     * 获取指定队列下一个数据
     *
     * @param key 指定队列
     * @return 数据对象
     */
    private static String getNext(String key) {
        return jedis.lindex(key, 0L);
    }

    /**
     * 追加数据到指定队列
     *
     * @param key 指定队列
     * @param sbv 数据对象
     */
    private static void append(String key, String sbv) {
        jedis.rpush(key, sbv);
    }

    /**
     * 删除指定队列数据， value不存在删除第一条；存在删除指定数据
     *
     * @param key 指定队列
     * @@param value 指定数据
     */
    private static void remove(String key, String value) {
        String removeString = value;
        if (StringUtils.isBlank(value)) {
            removeString = jedis.lpop(key);
        }
        if (StringUtils.isNotBlank(removeString)) {
            jedis.lrem(key, 1L, removeString);
        }
    }

    /**
     * Gets driver.
     * 安全的方式从列表后面返回数据
     *
     * @return the driver
     */
    public static TmsQueueDriverVo getDriverBySafeWay() {
        jedis = HYCUtils.getJedis();
        try {
            String data = jedis.brpoplpush(ZL_RS_DRIVER, ZL_RS_DRIVER, 20);
            return JSONObject.parseObject(data, TmsQueueDriverVo.class);
        } finally {
            jedis.close();
        }
    }


    //****************************************************急发单******************************************************/

	/**
	 * 追加急发订单到队列
	 * @param eov 数据对象
	 */
	public static void appendQuickOrder(TmsQueueOrderVo eov) {
		jedis = HYCUtils.getJedis();
		try {
			eov.setTime(DateUtils.getStringFromDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            // 普通  isUrgent (0:不加急，1:加急)
			Boolean isUrgent = eov.getUrgent();
			String resource = JSONObject.toJSONString(eov);
			System.out.println("==========resource==========" + resource);
			if (null == isUrgent || !isUrgent) {
				append(ZL_RS_QUICK_ORDER, resource);
				return;
			}
			jedis.lpush(ZL_RS_QUICK_ORDER, resource); // 加急

		} finally {
			jedis.close();
		}
	}

	/**
	 * 删除急发队列中指定订单对象。运单id和tms流水号，那个方便传递哪个
	 * @param waybillId 运单id
	 * @param tmsSerialNo tms流水号
	 */
	public static void removeQuickOrder(String waybillId, String tmsSerialNo) {
		jedis = HYCUtils.getJedis();
		try {
			Long lengthTem = getQueueLength(ZL_RS_QUICK_ORDER);
			for (long i = 0; i < lengthTem; i++) {
				String data = getDataByIndex(ZL_RS_QUICK_ORDER, i);
				if (StringUtils.isNotBlank(data)) {
					TmsQueueOrderVo tqov = JSONObject.parseObject(data, TmsQueueOrderVo.class);
					// 防止null导致系统异常
					if (StringUtils.isBlank(waybillId)) {
						waybillId = "";
					}
					if (StringUtils.isBlank(tmsSerialNo)) {
						tmsSerialNo = "";
					}
					if (tqov.getWaybillId().equals(waybillId) || tqov.getTmsSerialNo().equals(tmsSerialNo)) {
						remove(ZL_RS_QUICK_ORDER, data);
						return;
					}
				}
			}
		} finally {
			jedis.close();
		}
	}

    /**
     * 获取缓存急发订单数据
     *
     * @return 结果集
     */
    public static List<TmsQueueOrderVo> quickOrderList() {
        jedis = HYCUtils.getJedis();
        List<TmsQueueOrderVo> rtnList = new ArrayList<>();
        try {
            List<String> list = jedis.lrange(ZL_RS_QUICK_ORDER, 0, -1);
            if (null != list) {
                for (String s : list) {
                    rtnList.add(JSONObject.parseObject(s, TmsQueueOrderVo.class));
                }
            }
        } finally {
            jedis.close();
        }
        return rtnList;
    }


    /**
     * 获取缓存急发运单的数量
     * @return
     */
    public static long getAmount4QuickOrder(){
        Long lengthTem = getQueueLength(ZL_RS_QUICK_ORDER);
        return  lengthTem;
    }

}
